/*
 * Created on 2005-8-30
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.yeqiangwei.commons.ip;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author wang
 * 
 *         TODO To change the template for this generated type comment go to
 *         Window - Preferences - Java - Code Style - Code Templates
 */
public class NIODemo {

	String ipFile = "/opt/www/yqw-main/src/main/webapp/WEB-INF/index/QQWry.dat";
	RandomAccessFile file = null;
	FileChannel fc = null;
	MappedByteBuffer mbb = null;

	/**
     * 
     */
	public NIODemo() {
	}

	public static void main(String[] args) {
		NIODemo nio = new NIODemo();
		nio.init();
		System.out.println(nio.getString());
		nio.destory();
	}

	public void init() {
		try {
			file = new RandomAccessFile(ipFile, "r");
			fc = file.getChannel();
			System.out.println(file.length());
			mbb = fc.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public String getString() {
		byte[] rs = new byte[1024];
		String result = "";
		ByteBuffer bb = mbb.get(rs, 0, 1024);
		char[] c = new char[bb.capacity()];
		for (int i = 0; i < 1024 / 4; i++) {
			c[i] = bb.getChar(i);
		}
		result = new String(c);
		//String s = IPUtils.getString(result, "gbk", "UTF-8");
		return result;
	}

	public void destory() {
		try {
			mbb.clear();
			fc.close();
			file.close();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
}
